<?php

/**
 * 大同-卓志 SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopzhuozhi;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class ShopzhuozhiApiClient
{
    private $account  = 'shopzhuozhi';
    protected $config;
    protected $RouteMap = [
        'createOrder'           => '/rest/big/receiveOrder',
    ];
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', '14');
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //商品下单组
        $orderGoodsList = [];
        $productAmt     = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
        
            //商品单价包含税金
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$quantity,3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney,(string)100,1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100,2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney,2);
            }
        
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount,2);
            //商品组
            $orderGoodsList[] = [
                'source'            => null,
                'gnum'              => $key+1,                
                'goodId'            => $item['supplier_skucode'],
                'barCode'           => "无",
                'amount'            => $buyAcount,
                'price'             => (float)$singleGoodsPrice,
                'goodPrice'         => (float)$singleGoodsPrice,
                'copGName'          => $item['goods_name'],
                'hsCode'            => null,
                'decTotal'          => $totalGoods,
                'nots'              => null,
                'custGoodsNo'       => null,
                'ciqGoodsNo'        => null,
                'batchNo'           => null,
                'assemCountry'      => null,
                'ciqAssemCountry'   => null,
                'qtyUnit'           => null,
                'spec'              => null,
                'storeStrategyId'   => null,
                'productionTime'    => null,
                'expDate'           => null,
                'ownerCode'         => null,
                'virtualOwner'      => null,
                'codeTs'            => null,
                'brand'             => null,
                'packageType'       => null,
                'qty1'              => null,
                'gQty1'             => null,
                'unit1'             => null,
                'qty2'              => null,
                'gQty2'             => null,
                'unit2'             => null,
                'grossWeight'       => null,
                'currency'          => null,
                'netWeight'         => null,
                'isGoodsRecord'     => null,
                'permissions'       => null,
            ];
            $productAmt = bcadd((string)$productAmt,(string)$totalGoods,2);
        }
        
        //实际下单金额
        $real_total_money = $orderInfo['real_total_money'];
        
        //优惠金额
        $discount_money = bcsub((float)$productAmt,(float)$real_total_money,2);
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //支付时间
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('Y-m-d H:i:s',$pay_time);
        
        //支付流水号
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        
        //电商平台信息
        $enterpriseNum = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        //支付公司信息
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyName = $apply_extends['payCommanyName'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $payCommanyName = $order['payCommanyName'] ? $order['payCommanyName'] : $payCommanyName;
         
        //创建订单数据
        $data = [
            'source'            => null,
            'orderId'           => $orderInfo['supplier_dsn'],
            'orderDate'         => date("Y-m-d H:i:s",time()),
            'packingMaterial'   => "",
            'warehouseId'       => $this->config['warehouseId'],
            'tpl'               => "",
            'orderType'         => (int)$this->config["orderType"],
            'customsType'       => (int)$this->config["customsType"],
            'electricCode'      => $enterpriseNum,
            'cbepcomCode'       => $enterpriseNum,
            'deliveryCode'      => null,
            'notes'             => null,
            'freightFcy'        => 0.00,
            'freightFcode'      => "CNY",
            'insuredFee'        => 0.00,
            'taxFcy'            => 0.00,
            'discount'          => (float)$discount_money,
            'buyerName'         => $orderInfo['buyer_realname'],
            'buyerIdType'       => "1",
            'buyerIdNumber'     => $orderInfo['buyer_idcard'],
            'buyerTelephone'    => $orderInfo['buyer_phone'],
            'buyerRegNo'        => $orderInfo['buyer_phone'],
            'grossWeight'       => "",
            'netWeight'         => "",
            "orderStatus"       => "S",
            "busiMode"          => $this->config["busiMode"],
            "customsCode"       => $this->config["customsCode"],
            "ciqbCode"          => "0",
            'stationbCode'      => null,
            'statisticsFlag'    => null,
            'bakbCode'          => null,
            'logisticsNo'       => null,
            'ordExcStatus'      => null,
            'forSellComp'       => null,
            'forSellCompName'   => null,
            'tradeUnitCode'     => null,
            'tradeUnitName'     => null,
            "shippernCode"      => "142",
            'fCode'             => null,
            "taxFcode"          => "CNY",
            "payDate"           => $pay_time,
            'shipDate'          => null,
            'inputDate'         => null,
            'payNots'           => null,
            'ogNots'            => null,
            'blno'              => null,
            'trans'             => null,
            'transNo'           => null,
            'changeFlag'        => null,
            'reDeclare'         => null,
            'tradeMode'         => null,
            'shipperName'       => null,
            'shipperAddress'    => null,
            'shipperPhone'      => null,
            'insurCurr'         => null,
            'insurMark'         => null,
            'otherCurr'         => null,
            'otherRate'         => null,
            'otherMark'         => null,
            'otherPaymentCurr'  => null,
            "otherPayment"      => 0,
            "payNo"             => $pay_sn,
            "payPcomName"       => $payCommanyName,
            "payCopNo"          => $payCommanyCode,
            "agentCode"         => $enterpriseNum,
            "agentName"         => $enterpriseName,
            'opType'            => null,
            "payType"           => "M",
            "payStatus"         => "D",
            'payCurr'           => null,
            'payorName'         => null,
            'activePayComp'     => null,
            "acturalPaid"       => (float)$real_total_money,
            "fromEplat"         => 0,
            'printHeader'       => null,
            'commonField'       => null,
            'isStoreStrategy'   => "0",
            "vmiFlag"           => 0,
            "ownerFlag"         => 0,
            'cutMode'           => null,
            'transMode'         => null,
            'packNo'            => 1,
            'wrapType'          => null,
            'sendCity'          => null,
            'totalValue'        => null,
            'goodsInfo'         => null,
            'orderBatchNo'      => null,
            "recipient"         => [
                'source'            => null,
                'name'              => $orderInfo['receive_name'],
                'receiveType'       => 1,
                'receiveNo'         => $orderInfo['receive_name'],
                'mobilePhone'       => $orderInfo['receive_name'],
                'phone'             => null,
                'country'           => '中国',
                'pod'               => null,
                'province'          => $orderInfo['province'],
                'city'              => $orderInfo['city'],
                'district'          => $orderInfo['district'],
                'address'           => $orderInfo['receive_address'],
                'postCode'          => null,
                'totalFavourable'   => 0,
                'sender'            => null,
                'receiver'          => null,
                'congratulations'   => null,
                'transportDay'      => null,
                'recipientProvincesCode'=> null,
                'permissions'       => null,
            ],
            'goodList'          => $orderGoodsList,
            'shipid'            => "",
            'permissions'       => null,
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method = $param['method'];
        $url    = $this->config['baseurl'].$this->RouteMap[$method];
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => ["Content-Type: application/json"],
            ],
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['status']) && $resHttp['status'] == 1 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        $message = isset($resHttp['notes']) ? $resHttp['notes'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}